package com.java.study.interceoter;

import com.google.gson.Gson;
import com.java.study.common.utils.JwtUtil;
import com.java.study.common.utils.R;
import io.jsonwebtoken.Claims;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

public class LoginIntercepter implements HandlerInterceptor {


	private static final Gson gson = new Gson();

	/**
	 * 进入controller之前进行拦截
	 */
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {


		String token = request.getHeader("token") != null ? request.getHeader("token") : request.getParameter("token");

		if (token != null) {
			Claims claims = JwtUtil.parseJWT(token);
			if (claims != null) {
				Integer userId = Integer.valueOf(claims.getId());
				String name = claims.getSubject();

				request.setAttribute("user_id", userId);
				request.setAttribute("name", name);

				return true;
			}
		}

		sendJsonMessage(response, R.error("请登录"));
		return false;
	}


	/**
	 * 响应数据给前端
	 */
	public static void sendJsonMessage(HttpServletResponse response, Object obj) throws IOException {

		response.setContentType("application/json; charset=utf-8");
		PrintWriter writer = response.getWriter();
		writer.print(gson.toJson(obj));
		writer.close();

		response.flushBuffer();

	}


}
